package com.hula.onion.book.server.spider.platforms.zhongrongbao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.cookie.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by work on 2018/1/23.
 */
@Component("zhongRongBaoSpider")
public class ZhongRongBaoSpider extends SpiderCommon {

    @Autowired
    private ZhongRongBaoSpiderHelper spiderHelper;

    private static final String SECURITY_URL = "https://www.zrbao.com/zrbaoSecurity";

    @Override
    public CommonResponse execute() {
        String securityStr = HttpUtils.get(SECURITY_URL, getHttpContext());
        if (StringUtils.isEmpty(securityStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONObject securityJson = JSON.parseObject(securityStr);
        String getDataUrl;
        if ("success".equals(securityJson.getString("json"))) {
            getDataUrl = securityJson.getJSONObject("data").getString("dataFunServer");
            String loginInfo = HttpUtils.post(getDataUrl,
                    spiderHelper.installRequestParams(loginForm),
                    getHttpContext());
            if (StringUtils.isEmpty(loginInfo)) {
                return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
            }
            JSONObject loginJson = JSON.parseObject(loginInfo);
            String sid = null;
            if ("SUCC".equals(loginJson.getJSONObject("head").getString("state"))) {
                for (Cookie c : getHttpContext().getCookieStore().getCookies()) {
                    if ("ZRBAO_TOKEN".equals(c.getName())) {
                        sid = c.getValue();
                        break;
                    }
                }
                Map<String, Object> accountParam = spiderHelper.installAccountParams(sid);
                String accountStr = HttpUtils.post(getDataUrl, accountParam, getHttpContext());
                return spiderHelper.parseAccountBalance(accountStr);
            } else {
                return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
            }
        }
        return new CommonResponse(ResponseStatusEnum.FAIL);
    }
}
